package ptkdemo.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.googlecode.gwtptk.client.PageOf;
import ptkdemo.client.DemoService;
import ptkdemo.client.User;
import ptkdemo.client.UserFilter;

import java.util.ArrayList;

/**
 * PtkDemoServlet.
 *
 * @author Richard "Virgo" Richter (virgo47@gmail.com)
 */
public class PtkDemoServlet extends RemoteServiceServlet implements DemoService {
	private User[] userDb = {
		new User("Peter Hood", "Treehuggins 4", "peter.hood@jmail.orp", "hope there is noone with that email ;-)"),
		new User("Mark Kevendish", "Cyclotron 12/4, Bastila", "mrkkvndsh@jotmail.mom", "Fast one"),
		new User("Richard Richter", "Somewhere in Slovakia", "virgo47@gmail.com", null),
		new User("Someone Else", "Neverland 36", null, "never responds to instant messaging"),
		new User("Henry Plotter", "Hermiona St. 222", "hp@hp.hp", null),
		new User("Flora Brandistock", null, "flora@brandistock.name", ""),
		new User("Adela Yehiel", "", "", ""),
		new User("Irena Marsaili", "", "", ""),
		new User("Andraste Yuzuki", "", "", ""),
		new User("Katarina Blandus", "", "", ""),
		new User("Zara Gilberto", "", "", ""),
		new User("Fedora Fiona", "", "", ""),
		new User("Janie Waqar", "", "", ""),
		new User("Troy Tarak", "", "", ""),
		new User("Tania Bumbalough", "", "", ""),
		new User("Christian Poovey", "", "", ""),
		new User("Kelly Deere", "", "", ""),
		new User("Earlene Cost", "", "", ""),
		new User("Ashlee Yoakum", "", "", ""),
		new User("Hugh Strate", "", "", ""),
		new User("Fernando Gleaton", "", "", ""),
		new User("Nita Githens", "", "", ""),
		new User("Kelly Hofman", "", "", ""),
		new User("Tanisha Swinderman", "", "", ""),
	};

	@Override
	public PageOf<User> listUsers(UserFilter filter) {
		ArrayList<User> users = new ArrayList<User>();
		int counter = 0;
		for (User user : userDb) {
			if (filter.getName() == null || user.getName().contains(filter.getName())) {
				if (!filter.isPaged() || counter >= filter.getResultOffset() && counter < filter.getResultOffset() + filter.getPageSize()) {
					users.add(user);
				}
				counter++;
			}
		}
		PageOf<User> page = new PageOf<User>(users, 0, 0, users.size());
		if (filter.isPaged()) {
			page.setPageSize(filter.getPageSize());
			page.setFirstResultOffset(filter.getResultOffset());
			page.setResultsCount(counter);
		}
		return page;
	}
}
